<template>
    <div v-loading="isLoading || isExporting" class="meter-report-container">
        <!-- 日期选择和导出区域 -->
        <div class="meter-report-header">
            <CustomDatePicker width="14rem" border round v-model="dateRange" />
            <el-checkbox v-model="showUnknownRate" label="显示子表的不明水率"></el-checkbox>
            <div style="margin-left:auto ;">
                <span style="font-size: var(--font-size-small);margin-right: var(--gap-small);">表格布局</span>
                <el-segmented class="custom-style" v-model="tableSize" :options="sizeOptions" />
            </div>
            <!-- 新增刷新按钮 -->
            <el-button type="primary" :loading="isLoading" @click="handleRefresh">
                <template #icon>
                    <i class="fa fa-refresh"></i>
                </template>
                刷新
            </el-button>
            <el-button type="success" :loading="isExporting" @click="handleExport">
                <template #icon>
                    <SvgIcon icon="download"></SvgIcon>
                </template>
                导出
            </el-button>
        </div>

        <!-- 表格区域 - 修改为使用shouldRenderTable控制渲染 -->
        <vxe-table v-if="shouldRenderTable" :row-config="{ isCurrent: true, isHover: true }" :padding="false"
            :resizable-config="resizableConfig" :size="tableSize" :style="{ fontSize: getFontSize() }"
            class="meter-report-table" height="93%" show-footer ref="tableRef" border align="center"
            :data="meterTableData" :element-loading-text="isExporting ? '正在导出所有数据请稍等...' : '加载中...'"
            :column-config="columnConfig" :tree-config="treeConfig" :footer-data="footerData"
            :export-config="exportConfig">
            <!-- 固定列 -->
            <vxe-column tree-node fixed="left" field="meter_code" title="表计编号" width="200">
                <template #default="{ row }">
                    <span>{{ row.meter_code }}</span>
                    <el-tag v-if="row.level === 1 && !first_nodes.includes(row.id) && !row.hasChild" size="small"
                        type="info" style="margin-left: 8px">不纳入不明水计算</el-tag>
                </template>
                <template #footer="{ row }">
                    <span>{{ row.meter_code }}</span>
                    <el-tooltip v-if="row.meter_code === '总不明水率'" content="" placement="top">
                        <template #content>
                            不明水包含漏水、未计量用水。<br>不明水率准确度还受表计精度影响，<br>通常在正负8%以内视为正常。 </template>
                        <i style="margin-left: 4px;" class="fa fa-question-circle"></i>
                    </el-tooltip>
                </template>
            </vxe-column>
            <vxe-column fixed="left" width="100" show-overflow="tooltip" title="供应点位">
                <template #default="{ row }">
                    {{ row.supply_region || '-' }}
                </template>
            </vxe-column>
            <vxe-column width="120" show-overflow="tooltip" field="installation_location" title="安装位置" />
            <vxe-column field="specification" width="100" title="规格" />
            <!-- 启读数 -->
            <vxe-column :width="cellWidth" field="startReading" title="启读数(m³)">
                <template #default="{ row }">
                    {{ row && row.startReading !== undefined ? (row.startReading === 0 ? '/' : row.startReading) :
                        '/' }}
                </template>
            </vxe-column>
            <!-- 动态日期列 -->
            <template v-for="(date, dateIndex) in dateColumns" :key="date">
                <vxe-colgroup :title="date">
                    <!-- 流量列模板 -->
                    <vxe-column :width="cellWidth" :field="`usage_${dateIndex}`" title="流量(m³)">
                        <template #default="{ row }">
                            <div style="display: flex; align-items: center; justify-content: center;">
                                {{ row ? formatFlowValue(row[`usage_${dateIndex}`]) : '/' }}
                            </div>
                        </template>
                        <template #footer="{ row }">
                            <div style="display: flex; align-items: center; justify-content: center;">
                                {{ row ? formatFlowValue(row[`usage_${dateIndex}`]) : '无数据' }}
                                <el-tooltip
                                    v-if="row && row.meter_code && row.meter_code.includes('不明水率') && parseFloat(row[`usage_${dateIndex}`]) > 10"
                                    content="不明水率超过10%，可能存在异常" placement="top">
                                    <i class="fa fa-exclamation-circle" style="color: #E6A23C; margin-left: 4px;"></i>
                                </el-tooltip>
                            </div>
                        </template>
                    </vxe-column>

                    <!-- 读数列模板 -->
                    <vxe-column :width="cellWidth" :field="`reading_${dateIndex}`" title="读数(m³)">
                        <template #default="{ row }">
                            {{ row ? formatReadingValue(row[`reading_${dateIndex}`]) : '/' }}
                        </template>
                    </vxe-column>
                </vxe-colgroup>
            </template>

            <!-- 总流量列 -->
            <vxe-column fixed="right" field="sum" :width="cellWidth" title="总流量(m³)">
                <template #default="{ row }">
                    {{ row && row.sum !== undefined ? row.sum : '/' }}
                </template>
            </vxe-column>
        </vxe-table>
    </div>
    <SubMeterDialog v-model:visible="dialogVisible" :meter-data="selectedMeterData" :date-columns="dateColumns"
        :table-size="tableSize" :fetch-data="fetchAndProcessMeterData" :load-child-nodes="loadChildNodes" />
</template>

<script setup>
import { ref, onMounted, watch, computed, reactive, nextTick } from "vue";
import { handleError } from "@/utils/handleError";
import { getMeterReportApi, getMeterInfoApi } from "@/api/meter";
import { getUnknownWaterApi } from "@/api/algorithm";
import CustomDatePicker from "@/components/header/CustomDatePicker.vue";
import { calculateWaterLossRate, sortMeterList, formatFlowValue, formatReadingValue, generateDateColumns, transformMeterData } from "@/utils/meterUtils";
import { useCompanyStore } from "@/stores/company";
import { getFormulaData, getFormulaList } from "@/utils/formula";
import { generateTimeConfig } from "@/utils/date";
import SubMeterDialog from "../components/SubMeterDialog.vue"
import { useIntelligentMeter } from "../../../../../composables/useIntelligentMeter";
import convertToTreeData from '@/utils/convertToTreeData';
import { getMetersByLevel } from '@/utils/getMetersByLevel';
import * as XLSX from 'xlsx';

let sizeOptions = [{ label: '紧凑', value: 'mini' }, { label: '标准', value: 'small' }, { label: '宽松', value: 'medium' }];
let cellWidth = ref("auto")
let tableSize = ref('small');
// 添加一个新的状态变量控制表格渲染
const shouldRenderTable = ref(true);

// 原本在 MeterStore 的数据
const treeDataForChart = ref([]);
const meterList = ref([]);
const meterLevels = ref([]);
const currentSelectedType = ref(1);

// 原本在 MeterStore 的方法
async function fetchMeterList(params = {}) {
    params = {
        type: currentSelectedType.value,
        ...params
    };
    try {
        isLoading.value = true;  // 添加loading状态
        const res = await getMeterInfoApi(params);
        if (res.code !== 200) {
            throw new Error(res.message || '获取表计列表失败');
        }
        // 对列表进行排序
        meterList.value = sortMeterList(res.data);
        treeDataForChart.value = await convertToTreeData(meterList.value);
        meterLevels.value = getMetersByLevel(treeDataForChart.value);
        return res;
    } catch (error) {
        handleError(error, '获取表计列表失败');
        return { code: 500, data: [] };
    } finally {
        isLoading.value = false;  // 确保loading状态被清除
    }
}

const getFontSize = () => {
    let fontSize = "14px"
    switch (tableSize.value) {
        case 'mini':
            fontSize = "12px"
            cellWidth.value = "60"
            break;
        case 'medium':
            fontSize = "18px"
            cellWidth.value = "140"
            break;
        default:
            fontSize = "14px"
            cellWidth.value = "100"
            break;
    }

    return fontSize;
}

const dialogVisible = ref(false);
const selectedMeterData = ref(null);
// 组件引用
const tableRef = ref(null);
const columnConfig = reactive({
    resizable: true
})
const resizableConfig = reactive({
    dragMode: 'fixed'
})
// 响应式数据
const tableTimeConfig = generateTimeConfig('monthly', 0) || { start_time: 0, end_time: 0 }
let dateRange = ref([
    tableTimeConfig.start_time,  // 月初
    tableTimeConfig.end_time     // 月末或今天的时间(根据generateTimeConfig的逻辑)
])

// 树形配置
const treeConfig = reactive({
    transform: true,
    rowField: "id",
    parentField: "parent_id",
    lazy: true,
    hasChild: "hasChild",
    showLine: true,
    loadMethod: ({ row }) => loadChildNodes(row),
    toggleMethod({ expanded, row }) {
        if (isExporting.value) return true
        if (row && row.level === 2) {
            dialogVisible.value = true;
            selectedMeterData.value = row;
        }
        return row && row.level === 1 ? true : false
    },
    iconOpen: 'vxe-icon-square-minus',
    iconClose: 'vxe-icon-square-plus'
});
// 状态管理

const exportConfig = {
    type: 'xlsx',
    includeFooter: true,
    useStyle: true,
    isFooter: true,
    isColgroup: true,
    isAllExpand: true,
    filename: '水表日统计报表',
    sheetName: '表计报表',
    modes: ['current'],
    original: false  // 导出渲染后的数据而不是原始数据，确保导出的是表格中显示的内容
}

const meterTableData = ref([]);
const footerDataRef = ref([]);
const isLoading = ref(false);
const isExporting = ref(false);
const Exported = ref(false);
const formulaList = ref([]);
const showUnknownRate = ref(false);
const companyStore = useCompanyStore();

// 计算属性：日期列
const dateColumns = computed(() => {
    if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
        return [];
    }
    return generateDateColumns(dateRange.value[0], dateRange.value[1]);
});

// 计算属性：footer数据
const footerData = computed(() => footerDataRef.value || []);

async function getTotalUnknownRate() {
    try {
        // 检查公司ID
        if (!companyStore?.currentCompany?.id) {
            return null;
        }

        // 检查日期范围
        if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
            return null;
        }

        const response = await getUnknownWaterApi({
            id: companyStore.currentCompany.id,
            start_time: dateRange.value[0],
            end_time: dateRange.value[1],
            interval: 'day'
        });

        // 检查响应数据
        if (!response || !response.data || !Array.isArray(response.data)) {
            return {
                level1Data: {},
                level2Data: {},
                unknownRateData: {},
                level1Sum: '/',
                level2Sum: '/',
                totalRate: '/'
            };
        }

        // 处理返回的每日数据
        const level1Data = {};
        const level2Data = {};
        const unknownRateData = {};
        let level1Sum = 0;
        let level2Sum = 0;
        let totalUnknownWater = 0;

        response.data.forEach((dayData, index) => {
            if (!dayData || !dayData.data) {
                level1Data[`usage_${index}`] = '/';
                level2Data[`usage_${index}`] = '/';
                unknownRateData[`usage_${index}`] = '/';
                return;
            }

            // 获取每日数据
            const topUsage = Number(dayData.data.top_usage || 0);
            const nextUsage = Number(dayData.data.next_usage || 0);
            const unknownWater = Number(dayData.data.unknown_water || 0);

            // 记录一级表数据
            level1Data[`usage_${index}`] = topUsage.toFixed(2);
            level1Sum += topUsage;

            // 记录二级表数据
            level2Data[`usage_${index}`] = nextUsage.toFixed(2);
            level2Sum += nextUsage;

            // 计算不明水率百分比
            const rate = topUsage ? (unknownWater / topUsage * 100).toFixed(2) + '%' : '0%';
            unknownRateData[`usage_${index}`] = rate;

            totalUnknownWater += unknownWater;
        });

        // 计算总的不明水率
        const totalRate = level1Sum ? (totalUnknownWater / level1Sum * 100).toFixed(2) + '%' : '0%';

        return {
            level1Data,
            level2Data,
            unknownRateData,
            level1Sum: level1Sum.toFixed(2),
            level2Sum: level2Sum.toFixed(2),
            totalRate
        };
    } catch (error) {
        handleError(error, '获取不明水率失败')
        return {
            level1Data: {},
            level2Data: {},
            unknownRateData: {},
            level1Sum: '/',
            level2Sum: '/',
            totalRate: '/'
        };
    }
}

async function fetchAndProcessMeterData(meter) {
    if (!meter || !meter.id) {
        return null;
    }

    if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
        return null;
    }

    try {
        const response = await getMeterReportApi({
            id: meter.id,
            start_time: dateRange.value[0],
            end_time: dateRange.value[1],
            interval: 'day',
        });

        // 检查响应数据
        if (!response) {
            return null;
        }

        return transformMeterData(meter, response);
    } catch (error) {
        handleError(error, `获取表计${meter.meter_code}的数据失败`);
        return null;
    }
}

async function updateFooterData() {
    try {
        // 获取API的数据
        const data = await getTotalUnknownRate();
        if (!data) {
            // 设置默认的/状态
            footerDataRef.value = getDefaultFooterData();
            return;
        }

        footerDataRef.value = [{
            meter_code: '一级表合计',
            ...data.level1Data,
            sum: data.level1Sum
        }, {
            meter_code: '二级表合计',
            ...data.level2Data,
            sum: data.level2Sum
        }, {
            meter_code: '总不明水率',
            ...data.unknownRateData,
            sum: data.totalRate
        }];

        // 添加公式数据，同时计算总流量
        if (formulaList.value && Array.isArray(formulaList.value)) {
            formulaList.value.forEach(formula => {
                if (!formula) return;

                let formulaSum = 0;
                // 遍历每个月的数据，累加计算总和
                dateColumns.value.forEach((_, index) => {
                    const value = formula[`usage_${index}`];
                    // 安全地将值转换为数字
                    const numValue = value !== undefined && value !== null ? Number(value) : 0;
                    if (!isNaN(numValue)) {
                        formulaSum += numValue;
                    }
                });

                footerDataRef.value.push({
                    meter_code: formula.name || '未命名公式',
                    ...formula,
                    sum: formulaSum.toFixed(2)
                });
            });
        }
    } catch (error) {
        // 设置默认的/状态
        footerDataRef.value = getDefaultFooterData();
    }
}

function getDefaultFooterData() {
    const defaultData = [{
        meter_code: '一级表合计',
        sum: '/'
    }, {
        meter_code: '二级表合计',
        sum: '/'
    }, {
        meter_code: '总不明水率',
        sum: '/'
    }];

    // 为每一行添加日期列的空数据
    if (dateColumns.value && Array.isArray(dateColumns.value)) {
        defaultData.forEach(row => {
            dateColumns.value.forEach((_, index) => {
                row[`usage_${index}`] = '/';
                row[`reading_${index}`] = '/';
            });
        });
    }

    return defaultData;
}

async function loadChildNodes(parentNode) {
    if (!parentNode || !parentNode.customChildren) {
        return [];
    }

    try {
        // 检查customChildren是否为数组
        if (!Array.isArray(parentNode.customChildren)) {
            return [];
        }

        const promises = parentNode.customChildren.map(child => {
            if (!child) return Promise.resolve(null);
            // 确保子节点数据包含 supply_region
            return fetchAndProcessMeterData({
                ...child,
                supply_region: child.supply_region || '-'
            });
        });

        const children = await Promise.all(promises);
        const validChildren = children;

        // 只在非最后一级的表计上添加不明水率
        if (showUnknownRate.value) {
            const waterLossRateNode = await calculateChildWaterLossRate(parentNode, validChildren);
            if (waterLossRateNode) {
                validChildren.push(waterLossRateNode);
            }
        }
        return validChildren;
    } catch (error) {
        handleError(error, '加载子节点失败');
        return [];
    }
}

async function calculateChildWaterLossRate(parentNode, children) {
    if (!parentNode || !children || !Array.isArray(children)) {
        return null;
    }

    const waterParentLossRate = {};
    let totalParentFlow = 0;
    let totalChildFlow = 0;

    // 确保dateColumns存在且为数组
    if (!dateColumns.value || !Array.isArray(dateColumns.value)) {
        return null;
    }

    dateColumns.value.forEach((_, index) => {
        // 安全获取父节点流量
        const parentFlow = parentNode[`usage_${index}`] !== undefined && parentNode[`usage_${index}`] !== null
            ? Number(parentNode[`usage_${index}`])
            : 0;

        // 安全计算子节点总流量
        let childFlow = 0;
        children.forEach(child => {
            if (!child || !child.meter_code || child.meter_code.includes('不明水率')) {
                return;
            }

            const childFlowValue = child[`usage_${index}`];
            if (childFlowValue !== undefined && childFlowValue !== null) {
                const numValue = Number(childFlowValue);
                if (!isNaN(numValue)) {
                    childFlow += numValue;
                }
            }
        });

        totalParentFlow += parentFlow;
        totalChildFlow += childFlow;
        waterParentLossRate[`usage_${index}`] = calculateWaterLossRate(parentFlow, childFlow);
    });

    return {
        meter_code: (parentNode.meter_code || '未知表计') + "不明水率",
        ...waterParentLossRate,
        sum: 0
    };
}

function initFooterData() {
    const initialFooter = [
        {
            meter_code: '一级表合计',
            sum: '正在计算中'
        },
        {
            meter_code: '二级表合计',
            sum: '正在计算中'
        },
        {
            meter_code: '总不明水率',
            sum: '正在计算中'
        }
    ];

    // 为每一行添加日期列的数据
    if (dateColumns.value && Array.isArray(dateColumns.value)) {
        initialFooter.forEach(row => {
            dateColumns.value.forEach((_, index) => {
                row[`usage_${index}`] = '正在计算中';
                // 如果有读数列，也添加
                row[`reading_${index}`] = '正在计算中';
            });
        });
    }

    footerDataRef.value = initialFooter;
}

const { scrollToLatest } = useIntelligentMeter({
    tableRef,
})
let first_nodes = ref([])

async function fetchMeterReport() {
    if (isLoading.value) return;

    try {
        meterTableData.value = [];
        isLoading.value = true;

        // 日期变化时，触发表格重新渲染
        shouldRenderTable.value = false;
        await nextTick();
        shouldRenderTable.value = true;

        // 检查公司ID
        const company = companyStore?.currentCompany;
        if (!company || !company.id) {
            isLoading.value = false;
            return;
        }

        let company_id = company.id;

        // 检查表计数据
        if (!treeDataForChart.value || !Array.isArray(treeDataForChart.value)) {
            isLoading.value = false;
            return;
        }

        // 直接使用表计树数据，不再从 meterStore 获取
        const meters = treeDataForChart.value;

        // 获取表计数据
        const promises = meters.map(meter => {
            if (!meter) return Promise.resolve(null);
            return fetchAndProcessMeterData(meter);
        });

        const results = await Promise.all(promises);
        meterTableData.value = results.filter(Boolean);

        // 安全获取first_nodes
        first_nodes.value = [];
        meterTableData.value.forEach(element => {
            if (element && element.engine_id === 10 && element.meter_id) {
                try {
                    const ids = element.meter_id.split(',').map(id => +id).filter(id => !isNaN(id));
                    first_nodes.value.push(...ids);
                } catch (error) {

                }
            }
        });

        // 先结束加载状态
        isLoading.value = false;

        // 确保表格完全渲染
        await nextTick();
        // 然后执行表格操作
        const table = tableRef.value;
        if (table) {
            try {
                await table.setAllTreeExpand(true);
                await scrollToLatest();
            } catch (error) {

            }
        } else {

        }

        // 初始化页脚数据
        initFooterData();

        // 获取公式列表
        try {
            formulaList.value = await getFormulaList(company_id, '用水日报表') || [];
            formulaList.value = await getFormulaData(formulaList.value, dateColumns.value) || [];
        } catch (error) {
            handleError(error, '获取公式列表失败');
            formulaList.value = [];
        }

        // 更新footer数据
        await updateFooterData();

    } catch (error) {
        handleError(error, "获取水表数据失败");
        // 设置一个空的表格数据以防止界面出错
        meterTableData.value = [];
        footerDataRef.value = getDefaultFooterData();
    } finally {
        isLoading.value = false;
    }
}

// 新增刷新功能处理方法
async function handleRefresh() {
    try {
        // 重置Exported状态，确保下次导出时能重新展开节点
        Exported.value = false;

        // 显示刷新提示
        ElMessage({
            type: 'info',
            title: '提示',
            message: '正在刷新数据...',
        });

        // 重新获取表计数据
        await fetchMeterReport();

        // 刷新成功提示
        ElMessage({
            type: 'success',
            title: '成功',
            message: '数据刷新成功',
        });
    } catch (error) {
        handleError(error, "刷新数据失败", true);
    }
}

// 获取所有表计数据（展平树形结构）
async function getAllMeterDataFlat() {
    const allData = [];

    // 递归获取所有节点数据
    async function collectNodeData(nodes, level = 1) {
        for (const node of nodes) {
            if (!node) continue;

            // 添加当前节点，不添加缩进
            allData.push({
                ...node,
                level: level
            });

            // 获取子节点数据
            if (node.hasChild && node.customChildren) {
                const childrenData = await loadChildNodes(node);
                if (childrenData && childrenData.length > 0) {
                    await collectNodeData(childrenData, level + 1);
                }
            }
        }
    }

    // 开始收集所有表计数据
    await collectNodeData(meterTableData.value);

    return allData;
}

// 创建Excel表头结构
function createExcelHeaders() {
    const headers = [];
    const mergeRanges = [];

    // 第一行表头（主要列标题）
    const firstRow = [
        '表计编号', '供应点位', '安装位置', '规格', '启读数(m³)'
    ];

    // 添加动态日期列
    dateColumns.value.forEach(date => {
        firstRow.push(date, ''); // 每个日期占两列（流量和读数）
    });

    firstRow.push('总流量(m³)');
    headers.push(firstRow);

    // 第二行表头（子列标题）
    const secondRow = [
        '', '', '', '', '' // 前5列空白
    ];

    // 为每个日期添加流量和读数子标题
    dateColumns.value.forEach((date, index) => {
        secondRow.push('流量(m³)', '读数(m³)');

        // 记录需要合并的单元格范围（日期列）
        const colIndex = 5 + index * 2; // 5是前面固定列的数量
        mergeRanges.push({
            s: { r: 0, c: colIndex }, // 开始位置
            e: { r: 0, c: colIndex + 1 } // 结束位置
        });
    });

    secondRow.push('');
    headers.push(secondRow);

    // 为前5列添加合并单元格配置（第一行和第二行合并）
    for (let col = 0; col < 5; col++) {
        mergeRanges.push({
            s: { r: 0, c: col }, // 第一行
            e: { r: 1, c: col }  // 第二行
        });
    }

    // 为总流量列添加合并单元格配置
    const totalFlowCol = 5 + dateColumns.value.length * 2;
    mergeRanges.push({
        s: { r: 0, c: totalFlowCol },
        e: { r: 1, c: totalFlowCol }
    });

    return { headers, mergeRanges };
}

// 格式化数据行
function formatDataRow(row, rowIndex) {
    const dataRow = [
        row.meter_code || '', // 直接使用表计编号，不添加缩进
        row.supply_region || '-',
        row.installation_location || '',
        row.specification || '',
        row.startReading !== undefined ? (row.startReading === 0 ? '/' : row.startReading) : '/'
    ];

    // 添加动态日期列数据
    dateColumns.value.forEach((date, dateIndex) => {
        // 流量列
        const flowValue = row[`usage_${dateIndex}`];
        const errorValue = row[`error_${dateIndex}`];
        const formattedFlow = formatFlowValue(flowValue, errorValue);
        dataRow.push(formattedFlow);

        // 读数列
        const readingValue = row[`reading_${dateIndex}`];
        const formattedReading = formatReadingValue(readingValue, errorValue);
        dataRow.push(formattedReading);
    });

    // 总流量
    dataRow.push(row.sum !== undefined ? row.sum : '/');

    return dataRow;
}

// 主导出函数 - 修复样式居中问题
async function handleExport() {
    try {
        isExporting.value = true;

        ElMessage({
            type: 'info',
            message: '正在准备导出数据...',
        });

        // 1. 获取所有表计数据（展平）
        const allMeterData = await getAllMeterDataFlat();

        // 2. 创建Excel表头
        const { headers, mergeRanges } = createExcelHeaders();

        // 3. 创建工作簿和工作表
        const workbook = XLSX.utils.book_new();

        // 4. 准备数据
        const sheetData = [...headers];

        // 添加表计数据
        allMeterData.forEach((row, index) => {
            const dataRow = formatDataRow(row, index);
            sheetData.push(dataRow);
        });

        // 5. 添加footer汇总数据
        if (footerData.value && footerData.value.length > 0) {
            // 添加空行分隔
            sheetData.push([]);

            // 添加汇总标题
            sheetData.push(['汇总数据']);

            // 添加汇总数据
            footerData.value.forEach(footerRow => {
                const summaryRow = [
                    footerRow.meter_code || '',
                    '', '', '', '' // 空白列
                ];

                // 添加动态日期列的汇总数据
                dateColumns.value.forEach((date, dateIndex) => {
                    summaryRow.push(
                        footerRow[`usage_${dateIndex}`] || '/',
                        footerRow[`reading_${dateIndex}`] || '/'
                    );
                });

                summaryRow.push(footerRow.sum || '/');
                sheetData.push(summaryRow);
            });
        }

        // 6. 创建工作表
        const worksheet = XLSX.utils.aoa_to_sheet(sheetData);

        // 7. 设置列宽
        const columnWidths = [
            { wch: 20 }, // 表计编号
            { wch: 12 }, // 供应点位
            { wch: 15 }, // 安装位置
            { wch: 10 }, // 规格
            { wch: 12 }, // 启读数
        ];

        // 为动态日期列设置宽度
        dateColumns.value.forEach(() => {
            columnWidths.push({ wch: 12 }); // 流量列
            columnWidths.push({ wch: 12 }); // 读数列
        });

        columnWidths.push({ wch: 12 }); // 总流量列

        worksheet['!cols'] = columnWidths;

        // 8. 设置合并单元格
        if (mergeRanges.length > 0) {
            worksheet['!merges'] = mergeRanges;
        }

        // 9. 添加工作表到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, '表计报表');

        // 10. 生成文件名
        const startDate = new Date(dateRange.value[0]).toLocaleDateString('zh-CN');
        const endDate = new Date(dateRange.value[1]).toLocaleDateString('zh-CN');
        const fileName = `水表统计报表_${startDate}_${endDate}.xlsx`;

        // 11. 导出文件
        XLSX.writeFile(workbook, fileName);

        ElMessage({
            type: 'success',
            message: '导出成功！',
        });

    } catch (error) {
        console.error('导出失败:', error);
        ElMessage({
            type: 'error',
            message: '导出失败，请重试',
        });
        handleError(error, '导出失败');
    } finally {
        isExporting.value = false;
    }
}

// 监听数据变化
watch(
    [() => dateRange.value, () => treeDataForChart.value],
    () => {
        fetchMeterReport();
    },
    { deep: true }
);

watch(
    [() => showUnknownRate.value],
    () => {
        fetchMeterReport();
    },
    { deep: true }
);

// 监听公司改变
watch(
    () => companyStore.currentCompany,
    async (newCompany) => {
        if (newCompany) {
            // 重置Exported状态
            Exported.value = false;

            // 重新获取表计列表
            await fetchMeterList();

            // 重新获取数据
            await fetchMeterReport();
        }
    }
);

// 生命周期钩子
onMounted(async () => {
    try {
        currentSelectedType.value = 1;
        await fetchMeterList();
        fetchMeterReport();
    } catch (error) {
        handleError(error, "初始化失败");
    }
});
</script>
<style scoped>
.meter-report-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.meter-report-header {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}

.meter-report-body {
    flex: 1;
}
</style>